package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.HashMap;
import java.util.Map;

class ConstructBinaryTreeFromInorderAndPostorderTraversal {
    // 2023-04-28 15:01:05
    public static void main(String[] args) {
        Solution solution = new ConstructBinaryTreeFromInorderAndPostorderTraversal().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        Map<Integer, Integer> indexMap = new HashMap<>();

        public TreeNode buildTree(int[] inorder, int[] postorder) {
            int n = inorder.length;

            for (int i = 0; i < n; i++) {
                indexMap.put(inorder[i], i);
            }
            return mybuildTree(inorder, postorder, 0, n - 1, 0, n - 1);
        }

        private TreeNode mybuildTree(int[] inorder, int[] postorder,
                                     int inorder_left, int inorder_right,
                                     int postorder_left, int postorder_right) {
            if (postorder_left > postorder_right) {
                return null;
            }

            int root = postorder[postorder_right];
            Integer root_index = indexMap.get(root);
            // 左子树的长度
            int length = root_index - inorder_left;

            TreeNode rootNode = new TreeNode(root);
            rootNode.left = mybuildTree(inorder, postorder,
                    inorder_left, root_index - 1,
                    postorder_left, postorder_left + length-1);
            rootNode.right = mybuildTree(inorder, postorder,
                    root_index + 1, inorder_left,
                    postorder_left + length, postorder_right - 1);
            return rootNode;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}